<template>
  <el-dialog
    :model-value="show"
    :title="dialogTitle"
    width="800px"
    append-to-body
    :before-close="handleClose"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    destroy-on-close
  >
    <div v-loading="loading">
      <div class="form-title copy-box">
        <span>团队信息</span>
        <span class="copy-btns" v-if="dialogType === '1' && canCopy">
          <el-button type="primary" link @click="copyModel">
            复制公司组织架构
          </el-button>
          <zx-header-tip
            trigger="click"
            effect="light"
            tip="点击此按钮，可将现有公司组织架构复制为系统内团队组织架构。复制后，系统内变更团队信息不会影响公司组织架构"
          />
        </span>
      </div>
      <el-form
        ref="detailFormRef"
        :model="detailForm"
        :rules="rules"
        label-width="100px"
        class="form-box"
      >
        <el-form-item label="所属上级：" prop="parent_id" style="width: 100%">
          <el-cascader
            v-model="detailForm.parent_id"
            :options="options"
            :disabled="dialogType !== '1'"
            :props="teamProps"
          />
        </el-form-item>
        <el-form-item label="团队名称：" prop="name" style="width: 100%">
          <el-input
            v-model="detailForm.name"
            maxlength="15"
            placeholder="请输入"
          />
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <el-button
        type="primary"
        :loading="submitLoading"
        :disabled="!show"
        @click="submitApply"
      >
        提交
      </el-button>
      <el-button type="info" @click="handleClose">取消</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ElMessageBox } from 'element-plus';
import {
  companyGroupAll,
  companyGroupCopy,
  companyGroupNew,
  companyGroupUpdate,
  canCopyTeam
} from '@/api/system';
const props = defineProps({
  show: {
    type: Boolean,
    default: false
  },
  defaultForm: {
    type: Object,
    default: () => {}
  },
  dialogType: {
    type: String,
    default: '1' // 1新增团队 2编辑 3新增下级
  },
  activeOranize: {
    type: Object,
    default: () => {}
  }
});

const teamProps = reactive({
  label: 'name',
  value: 'id',
  children: 'childs',
  checkStrictly: true,
  emitPath: false
});

const submitMsg = computed(() => {
  return {
    1: '新增团队成功',
    2: '编辑团队成功',
    3: '新增下级成功'
  }[props.dialogType];
});
const dialogTitle = computed(() => {
  return {
    1: '新增团队',
    2: '编辑团队',
    3: '新增下级'
  }[props.dialogType];
});

function getApi() {
  return {
    1: companyGroupNew,
    2: companyGroupUpdate,
    3: companyGroupNew
  }[props.dialogType];
}

const emit = defineEmits();

// 关闭
function handleClose() {
  emit('update:show', false);
}

// 提交
const detailFormRef = ref();
const submitLoading = ref(false);
async function submitApply() {
  try {
    await detailFormRef.value.validate();

    let params;
    if (['1', '3'].includes(props.dialogType)) {
      params = {
        parent_id: detailForm.value.parent_id,
        name: detailForm.value.name
      };
    } else {
      params = {
        id: detailForm.value.id,
        name: detailForm.value.name
      };
    }
    submitLoading.value = true;
    getApi()(params)
      .then(() => {
        $msg.success(submitMsg.value);
        emit('reload');
        handleClose();
      })
      .finally(() => {
        submitLoading.value = false;
      });
  } catch {
    console.log('团队管理-表单提交校验未通过');
  }
}

// 规则
const rules = reactive({
  parent_id: {
    required: true,
    message: '请选择所属上级',
    trigger: 'change'
  },
  name: {
    required: true,
    message: '请输入团队名称',
    trigger: 'change'
  }
});

// 复制
function copyModel() {
  ElMessageBox({
    title: '操作确认',
    message: '请确认是否复用公司现有公司架构作为系统团队？',
    type: 'warning',
    showCancelButton: true,
    beforeClose: (action, instance, done) => {
      if (action !== 'confirm') return done();
      instance.confirmButtonLoading = true;
      companyGroupCopy()
        .then(() => {
          done();
        })
        .finally(() => {
          instance.confirmButtonLoading = false;
        });
    }
  })
    .then(() => {
      $msg.success('复制公司组织架构成功');
      emit('reload');
      handleClose();
    })
    .catch(() => {
      console.log('取消复制公司组织架构');
    });
}

// 获取所属上级
const options = ref([]);
const loading = ref(false);
const canCopy = ref(false);
function getOptions() {
  loading.value = true;
  companyGroupAll()
    .then(res => {
      options.value = res.data || [];
    })
    .finally(() => {
      loading.value = false;
    });

  canCopyTeam().then(res => {
    canCopy.value = !res.data;
  });
}

// 初始化表单
const detailForm = ref({});
watch(
  () => props.show,
  val => {
    if (!val) return;
    // 赋默认值
    detailForm.value = JSON.parse(JSON.stringify(props.defaultForm));
    getOptions();

    if (['1'].includes(props.dialogType)) {
      detailForm.value.parent_id = props.activeOranize.id;
    }
    if (['2'].includes(props.dialogType)) {
      detailForm.value.parent_id = props.defaultForm.parent_id;
    }
    if (props.dialogType === '3') {
      detailForm.value.parent_id = props.defaultForm.id;
      detailForm.value.name = '';
    }
  }
);
</script>

<style lang="scss" scoped>
.copy-box {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.copy-btns {
  display: flex;
  align-items: center;
}
</style>
